/*
 * @Author: 吴世扬
 * @Date: 2022-10-10 10:31:20
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2025-02-27 16:25:08
 * @FilePath: /vue3-admin/src/store/modules/user.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { ref } from 'vue';
import { defineStore } from 'pinia';
import {
    getToken,
    setToken as setTokenCache,
    removeToken,
    getUserInfo as getLocaUserInfo,
    setUserInfo,
    removeUserInfo
} from '@/utils/auth';
import defaultAvatar from '@/assets/images/common/default-avatar.png';
import type { MyInfo } from '@/typings/api/my';
import { store } from '@/store';
import { getImageByToken } from '@/utils';

export const useUserStore = defineStore('user', () => {
    const localUserInfo = getLocaUserInfo();
    const token = ref(getToken() || '');

    const name = ref(localUserInfo ? localUserInfo.username : '某某');

    const avatar = ref(defaultAvatar);

    const role = ref<MyInfo['roleList'][0] | null>(null);

    const roleList = ref<MyInfo['roleList']>([]);

    const menuTree = ref<ExcludeType<MyInfo['menuTree'], undefined | null>>([]);

    const userInfo = ref<MyInfo | null>(null);

    const setToken = (data: string) => {
        token.value = data;
        setTokenCache(data);
    };

    const setMyInfo = (data: MyInfo) => {
        const userInfoData = data;
        if (userInfoData.roleList && userInfoData.roleList.length > 0) {
            roleList.value = userInfoData.roleList;
            role.value = userInfoData.roleList[0];
        }
        menuTree.value = userInfoData.menuTree || [];
        name.value = userInfoData.username || '佚名';
        avatar.value = userInfoData.avatar
            ? getImageByToken(userInfoData.avatar.token)
            : defaultAvatar;
        userInfo.value = userInfoData;
        setUserInfo(userInfoData);
    };

    const fedLogout = () => {
        token.value = '';
        avatar.value = '';
        role.value = null;
        roleList.value = [];
        menuTree.value = [];
        removeToken();
        removeUserInfo();
        return Promise.resolve();
    };

    return {
        token,
        name,
        avatar,
        role,
        roleList,
        menuTree,
        userInfo,
        setToken,
        setMyInfo,
        fedLogout
    };
});
export function useUserStoreHook() {
    return useUserStore(store);
}
